package com.app.newiptv.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.newiptv.R;
import com.app.newiptv.adaper.SitcomAdapter;
import com.app.newiptv.adaper.SitcomOrderAdapter;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.ProgramBean;
import com.app.newiptv.helper.MySQLiteOpenHelper;
import com.app.newiptv.helper.MySitcomIndexOpenHelper;
import com.app.newiptv.presenter.SitcomOrderPresenter;
import com.app.newiptv.utils.Paths;
import com.bumptech.glide.Glide;

import java.util.Arrays;

import static com.app.newiptv.utils.Paths.BASEPATH;


public class SitcomActivity extends Activity implements View.OnClickListener, View.OnFocusChangeListener {
    private RecyclerView mSitcom_rv;
    private RecyclerView mIndex_order_rv;
    private SitcomOrderPresenter sitcomOrderPresenter;
    private Button mPlay_btn;
    private Button mCollection_btn;
    private int currentPosition;
    private int allCount;
    private View focusView;
    private int id;
    private ImageView mImg_view;
    private TextView mFilm_name;
    private TextView mDirector_tv;
    private TextView to_star_tv;
    private TextView years_tv;
    private TextView introduce_tv;
    private TextView copyright_text;
    private TextView additional_text;
    private SQLiteDatabase readDatabase;
    private SQLiteDatabase writeDatabase;
    private MySQLiteOpenHelper sqlHelper;
    private ProgramBean.DataBean.ListBean listBean;
    private MySitcomIndexOpenHelper helper;
    public SQLiteDatabase readInstance;
    public SQLiteDatabase writeInstance;
    public String[] sitcomIndexs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sitcom);
        Bundle bundle = getIntent().getBundleExtra("bundle");
        id = bundle.getInt("id", 1);
        sqlHelper = MySQLiteOpenHelper.getInstance(this);
        readDatabase = sqlHelper.getReadInstance();
        writeDatabase = sqlHelper.getWriteInstance();
        helper = MySitcomIndexOpenHelper.getInstance(this);
        readInstance = helper.getReadInstance();
        writeInstance = helper.getWriteInstance();
        initView();
        initData();
        setLinsenter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sitcomOrderPresenter != null) {
            sitcomOrderPresenter.refresh();
            if(null!= mSitcom_rv.getAdapter())
            {
                mSitcom_rv.getAdapter().notifyDataSetChanged();
            }
//            sitcomOrderPresenter.loadItem(Paths.HOSTPATH + Paths.CHANNLE_DETAIL + "&ids=" + id, sitcomOrrderCallback);
        }

    }

    private void initView() {
        mSitcom_rv = (RecyclerView) findViewById(R.id.sitcom_rv);
        mIndex_order_rv = (RecyclerView) findViewById(R.id.index_order_rv);
        mPlay_btn = (Button) findViewById(R.id.play_btn);
        mCollection_btn = (Button) findViewById(R.id.collection_btn);

        mImg_view = (ImageView) findViewById(R.id.img_view);
        mFilm_name = (TextView) findViewById(R.id.film_name);
        mDirector_tv = (TextView) findViewById(R.id.director_tv);
        to_star_tv = (TextView) findViewById(R.id.to_star_tv);
        years_tv = (TextView) findViewById(R.id.years_tv);
        introduce_tv = (TextView) findViewById(R.id.introduce_tv);
        copyright_text = (TextView) findViewById(R.id.copyright_text);
        additional_text = (TextView) findViewById(R.id.additional_text);
    }

    private void initData() {
        mFilm_name.setTypeface(MyApplication.face);
        mDirector_tv.setTypeface(MyApplication.face);
        to_star_tv.setTypeface(MyApplication.face);
        years_tv.setTypeface(MyApplication.face);
        introduce_tv.setTypeface(MyApplication.face);
        sitcomOrderPresenter = new SitcomOrderPresenter(this);
        sitcomOrderPresenter.setDisplayed(true);
        sitcomOrderPresenter.loadItem(Paths.HOSTPATH + Paths.CHANNLE_DETAIL + "?ids=" + id, sitcomOrrderCallback);
        mPlay_btn.requestFocus();
        mPlay_btn.setNextFocusDownId(R.id.index_order_rv);
        mCollection_btn.setNextFocusDownId(R.id.index_order_rv);
    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    private void setLinsenter() {
        mPlay_btn.setOnClickListener(this);
        mCollection_btn.setOnClickListener(this);
        mPlay_btn.setOnFocusChangeListener(this);
        mCollection_btn.setOnFocusChangeListener(this);
        mPlay_btn.setNextFocusLeftId(R.id.play_btn);
        mCollection_btn.setNextFocusRightId(R.id.collection_btn);
        mIndex_order_rv.setOnKeyListener(new SetOnKey());
        mIndex_order_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b) {
                    focusView = mIndex_order_rv.getChildAt(currentPosition);
                    focusView.setBackgroundResource(R.drawable.bg_btn_orderitem);
                }
            }
        });
        mSitcom_rv.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (mSitcom_rv.getChildCount() > 0) {
                        mSitcom_rv.getChildAt(0).requestFocus();
                    }
                }
            }
        });
    }

    public static void arraySub(int[] data,int start,int end){
        for(int i=start;i<end;i++){
            System.out.print(data[i]+" ");
        }
    }

    private SitcomOrderPresenter.Callback sitcomOrrderCallback = new SitcomOrderPresenter.Callback() {
        @Override
        public void onError(int code, String msg) {

        }

        @Override
        public void onMovieCompleted(SitcomOrderPresenter presenter, int count) {
            SitcomOrderAdapter sitcomOrderAdapter = new SitcomOrderAdapter(presenter);
            ViewGroup.LayoutParams params = mIndex_order_rv.getLayoutParams();
            params.width = count * 120;
            mIndex_order_rv.setLayoutParams(params);
            mIndex_order_rv.setLayoutManager(new GridLayoutManager(SitcomActivity.this, count));
            sitcomOrderAdapter.setCount(count);
            mIndex_order_rv.setAdapter(sitcomOrderAdapter);
            currentPosition = count - 1;
            allCount = count;
            listBean = sitcomOrderPresenter.playDetailsBean.getList().get(0);
            Cursor cursor = readDatabase.query("RecodeCollect", null, "name=" + "'" +listBean.getVod_name() + "'"+" and " + "type=1", null, null, null, null);
            mCollection_btn.setVisibility(cursor.moveToFirst()?View.INVISIBLE:View.VISIBLE);
            cursor.close();
        }

        @Override
        public void onSitcomCompleted(SitcomOrderPresenter presenter, int count) {
            SitcomAdapter simpleAdapter = new SitcomAdapter(presenter, count, SitcomActivity.this);
            simpleAdapter.setSitcomName(listBean.getVod_name());
            simpleAdapter.setWriteDatabase(writeInstance);
            mSitcom_rv.setLayoutManager(new GridLayoutManager(SitcomActivity.this, 10));
            Cursor sitcomCursor = readInstance.query("SitcomIndex", null, "name="+ "'" +listBean.getVod_name() + "'", null, null, null, null);
            mSitcom_rv.setAdapter(simpleAdapter);
            if (sitcomCursor.moveToFirst()) {
                String sitcom_index = sitcomCursor.getString(sitcomCursor.getColumnIndex("sitcom_index"));
                sitcomIndexs = sitcom_index.split(",");
                simpleAdapter.setSitcomIndex(sitcomIndexs);
                simpleAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void setImg_view(String url) {
            Log.i("legendAdult", "setImg_view: " + url);
            Glide.with(SitcomActivity.this).load(BASEPATH + url).error(R.mipmap.iron).into(mImg_view);
        }

        @Override
        public void setFilm_name(String text) {
            mFilm_name.setText(text);
        }

        @Override
        public void setDirector_tv(String text) {
            mDirector_tv.setText(text);
        }

        @Override
        public void setTostar_tv(String text) {
            to_star_tv.setText(text);
        }

        @Override
        public void setYears_tv(String text) {
            years_tv.setText(text);
        }

        @Override
        public void setIntroduce_tv(String text) {
            introduce_tv.setText(text);
        }

        @Override
        public void setCopyright(String copyright) {
            copyright_text.setTypeface(MyApplication.face);
            copyright_text.setText("版权来源：" + copyright);
        }

        @Override
        public void setAllCount(String count) {
            additional_text.setText(count);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_btn:
                if (Contast.USE_GROUP.equals("3")) {
                    if (sitcomIndexs== null) {
                        ContentValues values = new ContentValues();
                        values.put("name", listBean.getVod_name());
                        values.put("sitcom_index", sitcomOrderPresenter.listContent.get(0).get(0).getName());
                        Log.i("legendki", "onClick: " + values);
                        writeInstance.insert("SitcomIndex",null,values);
                    }
                    else if (sitcomIndexs!= null && !Arrays.asList(sitcomIndexs).contains(listBean.getVod_name())) {
                        String sitcom_index = "";
                        for (int i = 0; i < sitcomIndexs.length; i++) {
                            sitcom_index = sitcom_index + sitcomIndexs[i] + ",";
                        }
                        sitcom_index = sitcom_index + sitcomOrderPresenter.listContent.get(0).get(0).getName() + ",";
                        ContentValues values = new ContentValues();
                        values.put("name", listBean.getVod_name());
                        values.put("sitcom_index", sitcom_index);
                        Log.i("legendki", "onClick: " + values);
                        writeInstance.update("SitcomIndex", values, "name=" + "'" + listBean.getVod_name() + "'", null);
                    }
                    sitcomOrderPresenter.toPlay(0);

                } else {
                    Toast.makeText(SitcomActivity.this, "您不是VIP", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.collection_btn:
                ContentValues values = new ContentValues();
                values.put("pic_url", listBean.getVod_pic());
                values.put("name", listBean.getVod_name());
                values.put("actor", listBean.getVod_actor());
                values.put("type", 1);
                values.put("collect_time", System.currentTimeMillis());
                values.put("movie_id", listBean.getVod_id());
                values.put("movie_type", 1000);
                Log.i("legendki", "onClick: " + values);
                if (!writeDatabase.isOpen()) {
                    writeDatabase = sqlHelper.getWriteInstance();
                }
                writeDatabase.insert("RecodeCollect",null,values);
                mCollection_btn.setVisibility(View.INVISIBLE);
                break;
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.play_btn:
                if (hasFocus) {
                    mPlay_btn.setBackgroundResource(R.mipmap.pd_play_focused);
                } else {
                    mPlay_btn.setBackgroundResource(R.mipmap.pd_play_normal);
                }
                break;
            case R.id.collection_btn:
                if (hasFocus) {
                    mCollection_btn.setBackgroundResource(R.mipmap.pd_collect_focused);
                } else {
                    mCollection_btn.setBackgroundResource(R.mipmap.pd_collect_normal);
                }
                break;
        }
    }


    private class SetOnKey implements View.OnKeyListener {

        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() == KeyEvent.ACTION_DOWN) {
                focusView.setBackgroundResource(0);
                currentPosition++;
                if (currentPosition >= allCount) {
                    currentPosition = 0;
                }
                View focV = mIndex_order_rv.getChildAt(currentPosition);
                focV.setBackgroundResource(R.drawable.bg_btn_orderitem);
                focusView = focV;
                sitcomOrderPresenter.loadSitcom(currentPosition);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                focusView.setBackgroundResource(0);
                currentPosition--;
                if (currentPosition < 0) {
                    currentPosition = allCount - 1;
                }
                View focV = mIndex_order_rv.getChildAt(currentPosition);
                focV.setBackgroundResource(R.drawable.bg_btn_orderitem);
                focusView = focV;
                sitcomOrderPresenter.loadSitcom(currentPosition);
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
                focusView.setBackgroundResource(0);
                //Toast.makeText(SitcomActivity.this, "向上", Toast.LENGTH_SHORT).show();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && event.getAction() == KeyEvent.ACTION_DOWN) {
                mSitcom_rv.requestFocus();
                focusView.setBackgroundResource(0);
                //Toast.makeText(SitcomActivity.this, "向下", Toast.LENGTH_SHORT).show();
                return true;
            }
            return false;
        }
    }
}
